<template>
  <q-dialog :model-value="modelValue" @update:model-value="handleDialogUpdate">
    <q-card :style="$q.screen.gt.xs ? 'min-width: 400px' : 'width: 100%'">
      <q-card-section>
        <div class="text-h6">{{ title }}</div>
      </q-card-section>

      <q-card-section class="q-pt-none">
        <q-list dense>
          <q-item v-for="(col, index) in visibleColumns" :key="index" tag="label">
            <q-item-section>
              <q-item-label>{{ col.label }}</q-item-label>
            </q-item-section>
            <q-item-section avatar>
              <q-toggle
                v-model="col.visible"
                color="primary"
                @update:model-value="updateColumnVisibility"
              />
            </q-item-section>
          </q-item>
        </q-list>
      </q-card-section>

      <q-card-actions align="right">
        <q-btn flat label="取消" color="primary" v-close-popup />
        <q-btn flat label="确定" color="primary" v-close-popup />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  columns: {
    type: Array,
    default: () => [],
  },
  title: {
    type: String,
    default: '显示/隐藏列',
  },
})

const emit = defineEmits(['update:columns', 'update:modelValue'])

// 只显示有 visible 属性的列
const visibleColumns = computed(() => {
  return props.columns.filter((col) => 'visible' in col)
})

const handleDialogUpdate = (value) => {
  emit('update:modelValue', value)
}

function updateColumnVisibility() {
  emit('update:columns', [...props.columns])
}
</script>
